<?php
class SaveMenu extends Action {
	/*
	 * (non-PHPdoc) @see Action::execute()
	 */
	public function execute($params) {
		check_login ( ADMIN_LOGIN_PAGE );
		$menu = rqsts ( array ('menu_name','menu_title','menu_id' => 0 ) );
		
		$mM = new WebMenuModel ();
		if (empty ( $menu ['menu_id'] )) {
			unset ( $menu ['menu_id'] );
		}
		$valid = $this->validate ( 'menu', $menu, $mM );
		
		if ($valid === true) {
			$md = rqset ( 'menu_default' );
			if ($md) {
				$menu ['menu_default'] = 1;
			}
			$rst = $mM->save ( $menu );
			if (! empty ( $rst )) {
				if ($md) {
					$mM->update ( array ('menu_default' => 0 ), array ('menu_id !=' => $rst ['menu_id'] ) );
				}
				if (rqset ( 'item' )) {
					$this->saveMenuItems ();
				}
				Response::redirect ( './?Ctlr=Menu&mid=' . $rst ['menu_id'] );
			} else {
				sess_add ( 'menu_info', $menu );
				sess_add ( 'page_tip_info', '<strong>出错啦!</strong>' . $groupModel->last_error_msg () );
				if (! isset ( $menu ['menu_id'] )) {
					Response::redirect ( './?Ctlr=Menu&suc=0&op=add' );
				} else {
					Response::redirect ( './?Ctlr=Menu&suc=0&mid=' . $menu ['menu_id'] );
				}
			}
		} else {
			sess_add ( 'menu_info', $menu );
			sess_add ( 'page_tip_info', '<strong>出错啦!</strong><p>' . implode ( "<br/>", $valid ) );
			Response::redirect ( './?Ctlr=Menu&suc=0&op=add' );
		}
	}
	private function saveMenuItems() {
		$items = rqst ( 'item', array () );
		if (empty ( $items )) {
			return true;
		}
		$miM = new WebMenuItemModel ();
		$miM->begin ();
		foreach ( $items as $item_id => $item ) {
			$item ['menuitem_id'] = $item_id;
			$rst = $miM->save ( $item );
			if ($rst === false) {
				$miM->rollback ();
				return false;
			}
		}
		$miM->commit ();
		return true;
	}
}